#!/bin/bash

# Weather System Docker部署脚本

set -e

echo "=== Weather System Docker 部署脚本 ==="

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo "错误: Docker未安装，请先安装Docker"
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    echo "错误: Docker Compose未安装，请先安装Docker Compose"
    exit 1
fi

# 获取脚本参数
ENVIRONMENT=${1:-production}
BUILD_OPTION=${2:-build}

echo "部署环境: $ENVIRONMENT"
echo "构建选项: $BUILD_OPTION"

# 设置docker-compose文件
if [ "$ENVIRONMENT" = "development" ]; then
    COMPOSE_FILE="docker-compose.dev.yml"
    echo "使用开发环境配置"
elif [ "$ENVIRONMENT" = "production" ]; then
    COMPOSE_FILE="docker-compose.yml"
    echo "使用生产环境配置"
else
    echo "错误: 无效的环境参数，支持: development, production"
    exit 1
fi

# 检查配置文件是否存在
if [ ! -f "$COMPOSE_FILE" ]; then
    echo "错误: 配置文件 $COMPOSE_FILE 不存在"
    exit 1
fi

# 创建必要的目录
echo "创建必要的目录..."
mkdir -p logs
mkdir -p data
mkdir -p monitoring/grafana/provisioning

# 设置环境变量
echo "设置环境变量..."
export COMPOSE_PROJECT_NAME=weather-system
export DOCKER_BUILDKIT=1

# 停止现有服务
echo "停止现有服务..."
docker-compose -f "$COMPOSE_FILE" down --remove-orphans

# 清理旧镜像(可选)
if [ "$BUILD_OPTION" = "clean" ]; then
    echo "清理旧镜像..."
    docker system prune -f
    docker-compose -f "$COMPOSE_FILE" build --no-cache
elif [ "$BUILD_OPTION" = "build" ]; then
    echo "构建镜像..."
    docker-compose -f "$COMPOSE_FILE" build
fi

# 启动服务
echo "启动服务..."
docker-compose -f "$COMPOSE_FILE" up -d

# 等待服务启动
echo "等待服务启动..."
sleep 30

# 检查服务状态
echo "检查服务状态..."
docker-compose -f "$COMPOSE_FILE" ps

# 显示健康检查状态
echo "=== 服务健康检查 ==="
services=("weather-api" "rabbitmq" "redis")

for service in "${services[@]}"; do
    echo "检查 $service 服务..."
    if [ "$ENVIRONMENT" = "development" ]; then
        service_name="${service}-dev"
    else
        service_name="weather-${service}"
    fi
    
    if docker ps --filter "name=$service_name" --filter "status=running" | grep -q "$service_name"; then
        echo "✅ $service 服务运行正常"
    else
        echo "❌ $service 服务异常"
    fi
done

# 显示访问地址
echo "=== 服务访问地址 ==="
if [ "$ENVIRONMENT" = "production" ]; then
    echo "🌐 前端应用: http://localhost:3000"
fi
echo "🔧 API文档: http://localhost:5197/api-docs"
echo "📊 Prometheus: http://localhost:9090"
echo "📈 Grafana: http://localhost:3001 (admin/admin123)"
echo "📝 Loki日志: http://localhost:3100 (通过Grafana访问)"
echo "🐰 RabbitMQ管理: http://localhost:15672 (admin/admin123)"
echo "🔍 Jaeger追踪: http://localhost:16686"

echo "=== 部署完成 ==="
echo "查看日志: docker-compose -f $COMPOSE_FILE logs -f"
echo "日志工具: ./scripts/logs.sh view api"
echo "停止服务: docker-compose -f $COMPOSE_FILE down"